using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using LeisureCenter.Core;

namespace LeisureCenter.Tools
{
    public abstract class SleepingThread
    {
        protected Thread thread;
        protected EventWaitHandle wakeupEvent;
        protected bool terminated;

        protected SleepingThread()
        {
            thread = new Thread(Execute);
            this.thread.IsBackground = true;
            wakeupEvent = new EventWaitHandle(false, EventResetMode.AutoReset);
            this.thread.Start();
        }

        protected void Execute()
        {
            while (!terminated && wakeupEvent.WaitOne() && !terminated)
            {
                try
                {
                    DoWork();
                }
                catch (Exception ex)
                {
                    Program.LeisureCenterInstance.HandleException(ex);
                }
            }
        }

        protected abstract void DoWork();

        public void Terminate()
        {
            terminated = true;
            Wakeup();
        }

        public virtual void Wakeup()
        {
            wakeupEvent.Set();
        }
    }
}
